#ifndef _MOTOR_H_
#define _MOTOR_H_

enum STATE_CODE {
    SC_STOPPED = 0,                         // 停止
    SC_FORWARD,                             // 前进直行
    SC_BACKWARD,                            // 后退直行
    SC_LOW_BAT                              // 低电压
};

enum MODE_CODE {
    MC_AUTO_RUN         = 0,                // 自动运行模式
    MC_TRACE,                               // 寻迹模式
    MC_REMOTE_CONTROL,                      // RF433 遥控模式
    MC_BLUETOOTH                            // 蓝牙遥控模式
};

struct {
    uint8_t  left_pwm = 59, right_pwm = 59; // 左右轮pwm初始值
    uint16_t turn_left_time  = 500,         // 左转时间(ms)
             turn_right_time = 500,         // 右转时间(ms)
             speed_time      = 500;         // 直行（前进或后退）时间(ms)
    uint8_t  state           = -1;          // 小车状态
    uint8_t  mode            = -1;          // 小车运行模式
} conf;

/** 直流电机结构体 */
typedef struct {
    uint8_t a, b;
} Motor;


Motor m0 = {M0_0, M0_1},        // 左轮电机
      m1 = {M1_0, M1_1};        // 右轮电机

void init_motor (Motor *motor) {
    pinMode (motor->a, OUTPUT);
    pinMode (motor->b, OUTPUT);
}

void forward (Motor *m) {
    digitalWrite (m->a, HIGH);
    digitalWrite (m->b, LOW);
}

void pwm_forward (Motor *m, int pwm) {
    analogWrite (m->a, pwm);
    digitalWrite (m->b, LOW);
}

void backward (Motor *m) {
    digitalWrite (m->a, LOW);
    digitalWrite (m->b, HIGH);
}

void pwm_backward (Motor *m, int pwm) {
    digitalWrite (m->a, LOW);
    analogWrite (m->b, pwm);
}

void pause (Motor *m) {
    digitalWrite (m->a, LOW);
    digitalWrite (m->b, LOW);
}

void forward () {
    forward (&m0);
    forward (&m1);
}

void backward () {
    backward (&m0);
    backward (&m1);
}

void pwm_forward (int pwm) {
    pwm_forward (&m0, pwm);
    pwm_forward (&m1, pwm);
}

void pwm_backward (int pwm) {
    pwm_backward (&m0, pwm);
    pwm_backward (&m1, pwm);
}

void left () {
    backward (&m0);
    forward (&m1);
}

void pwm_left (int pwm) {
    pwm_backward (&m0, pwm);
    pwm_forward (&m1, pwm);
}

void right () {
    forward (&m0);
    backward (&m1);
}

void pwm_right (int pwm) {
    pwm_forward (&m0, pwm);
    pwm_backward (&m1, pwm);
}

void pause () {
    pause (&m0);
    pause (&m1);
}

inline void move_on () {
    if (conf.state == SC_FORWARD) {
        pwm_forward (&m0, conf.left_pwm);
        pwm_forward (&m1, conf.right_pwm);
    } else if (conf.state == SC_BACKWARD) {
        pwm_backward (&m0, conf.left_pwm);
        pwm_backward (&m1, conf.right_pwm);
    } else if (conf.state == SC_STOPPED) {
        pause ();
    }
}
#endif // _MOTOR_H_
